package com.junjie.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.junjie.springcloud.entities.CommonResult;
import com.junjie.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author Yi Jun jie
 * @Date 2021/3/1 12:51
 */
@RestController
public class OrderController {

    private static final String PAYMENT_URL="http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/get/{id}")
    //@SentinelResource(value = "fallback", fallback = "handleFallback") //fallback只负责业务异常
    //@SentinelResource(value = "fallback", blockHandler = "handleBlockHandler")
    @SentinelResource(value = "fallback", fallback = "handleFallback", blockHandler = "handleBlockHandler")
    public CommonResult getPayment(@PathVariable("id")Long id){
        if(id >= 4){
            throw new IllegalArgumentException("非法参数异常...");
        }else {
            return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        }
    }

    //handleFallback出现代码异常的时候调用的兜底方法
    public CommonResult handleFallback(@PathVariable("id")Long id, Throwable e){
        Payment payment = new Payment(id, "null");
        return new CommonResult(444,  "兜底异常 handleFallback: " + e.getMessage(), payment);
    }

    //blockHandler的方法必须有这个参数 (违反配置规则的时候调用的兜底方法)
    public CommonResult handleBlockHandler(@PathVariable("id")Long id, BlockException e){
        Payment payment = new Payment(id, "null");
        return new CommonResult(445, "handleBlockHandler-sentinel 限流" + id + e.getMessage(), payment);
    }
}
